//
//  JoFileUpload.swift
//  JoTravel
//
//  Created by otisaldridge on 15/9/25.
//  Copyright © 2015年 zhuxietong. All rights reserved.

import Foundation
import UIKit
import Foundation
import Alamofire

//
//extension Alamofire {
//
//
//    static public func upload(
//        multipartFormData: @escaping (MultipartFormData) -> Void,
//        usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
//        to url: URLConvertible,
//        method: HTTPMethod = .post,
//        headers: HTTPHeaders? = nil,
//        encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?)
//    {
//        return SessionManager.default.upload(
//            multipartFormData: multipartFormData,
//            usingThreshold: encodingMemoryThreshold,
//            to: url,
//            method: method,
//            headers: headers,
//            encodingCompletion:encodingCompletion
//        )
//    }
//
//
//    public static func upload(
//        _ data: Data,
//        to url: URLConvertible,
//        method: HTTPMethod = .post,
//        headers: HTTPHeaders? = nil)
//        -> UploadRequest
//    {
//
//        return SessionManager.default.upload(data, to: url, method: method, headers: headers)
//
//    }
//
//
//}
//




//public protocol UPFile {
//    var data:Data {get set}
//    var name:String {get set}
//    var fileName:String {get set}
//    var mimeType:String {get set}
//
//}
//
//public struct UPImage:UPFile {
//
//    public init(image:UIImage){
//
//        if let data = UIImageJPEGRepresentation(image,1)
//        {
//            self.data = data
//        }
//        else
//        {
//            self.data = Data()
//        }
//
//    }
//
//
//    public var data: Data
//    public var name: String = "image"
//    public var fileName: String = "image.png"
//    public var mimeType: String = "image/png"
//
//}

extension JoTask {
    
    
    @discardableResult
    public func upload() ->JoTask
    {
        
        _  = self.post
        if let r = self.request
        {
            r.cancel()
        }
        
        if JoTask.debugLog
        {
            if self.if_log_request
            {
                print("JoTask:\(method_value)|\(url_value)\nparameters:\(getParams())\nheaders:\(getHeaders())")
            }
        }
        weak var wself = self
        let params = getParams()        
        self.request = AF.upload(multipartFormData: { (data) in
                if let ws = wself
                {
                    for (k,v) in params {
                        data.append(Data("\(v)".utf8), withName: k)
                    }
                    for item in ws.files
                    {
                        
                        data.append(item.data, withName: item.fieldName, fileName: item.fileName, mimeType: item.mimeType)
                    }
                    
                }
//            print("______S_S",da)
        }, to: url_value,headers: HTTPHeaders(getHeaders()))
        
        if let json_b = self.json_handle_block
        {
            weak var wself = self
            self.request?.responseJSON(completionHandler: { response in
                                
                
                if JoTask.debugLog
                {
                    if wself?.if_log_response ?? false
                    {
                        
                        print("JoTask response :\n code \(String(describing: response.response?.statusCode))  \(response)")
                    }
                }
            
                
                if response.error == nil
                {
                    let mode = wself?.apimode ?? .normal
                    switch mode{
                    case .module:
                        
                        JoTask.moduleModeHandle(mode,wself?.url_value,params,response.data,response,wself,json_b)
                            wself?.__drop()
                        return
                    default:
                        
                        if let info = wself?.dataHandle(wself,response,wself?.url_value,wself?.apimode)
                        {
                            json_b(info.status,info.message,info.obj,response,wself)
                            wself?.__drop()
                            return
                        }
                    }
                }
                else{
                    if JoTask.isCancel(response: response){
                        json_b(.cancel,"已取消数据请求".loc,NSMutableDictionary(), response,wself)
                        return
                    }
                    let code = response.response?.statusCode ?? 0
                    let codeStr = "\(code)"
                    if codeStr.starts(with: "5"){
                        json_b(.error,"数据服务错误(\(code))",NSMutableDictionary(), response,wself)
                        return
                    }
                    if codeStr.starts(with: "40"){
                        json_b(.error,"数据访问失败(\(code))",NSMutableDictionary(), response,wself)
                        return
                    }
                }
                
                json_b(.error,"获取数据失败(未知错误)！",response.value as AnyObject?,response,wself)
                wself?.__drop()
                return
                
            })
        }

        
        
        
//        Alamofire.upload(multipartFormData: { (data) in
//            if let ws = wself
//            {
//                for item in ws.files
//                {
//                    data.append(item.data, withName: item.fieldName, fileName: item.fileName, mimeType: item.mimeType)
//                }
//            }
//
//        }, to: url_value,headers:self.getHeaders()) { (encodingResult) in
//            switch encodingResult {
//
//            case .success(let upload, _, _):
//                upload.responseJSON {
//                    debugPrint($0)
//
//                    if let json_b = wself?.json_handle_block
//                    {
//                        if JoTask.debugLog
//                        {
//                            if wself?.if_log_response ?? false{
//
//                                print("JoTask response :   \($0)")
//
//                            }
//                        }
//
//                        if $0.result.isSuccess
//                        {
//                            if let info = wself?.dataHandle($0.result.value ?? NSMutableDictionary(),wself?.url_value,wself?.apimode)
//                            {
//                                json_b(info.status,info.message,info.obj,$0)
//                                wself?.__drop()
//                            }
//                        }
//
//
//
//                        json_b(.error,"获取数据失败(未知错误)！",$0.result.value as AnyObject?,$0)
//                        wself?.__drop()
//                        return
//
//                    }
//
//                }
//            case .failure(let encodingError):
//                if let json_b = self.json_handle_block
//                {
//
//                    let rs = Result<Any>.failure(encodingError)
//
//                    let r = DataResponse<Any>(request:nil, response: nil, data: nil, result: rs)
//
//                    json_b(.error,"获取数据失败(未知错误)！",nil,r)
//                    wself?.__drop()
//
//
//                }
//            }
//        }
        return self
    }
    
    
    @discardableResult
    public func easyUpload() ->JoTask
    {
        
        _  = self.post
        if let r = self.request
        {
            r.cancel()
        }
        
        if JoTask.debugLog
        {
            if self.if_log_request
            {
                print("JoTask:\(method_value)|\(url_value)\nparameters:\(getParams())\nheaders:\(self.getHeaders())")
            }
        }
        weak var wself = self
    
        EasyUploadTask.upload(to:url_value, tfiles: self.files,params:getParams(),headers:self.getHeaders()) { (object, data, response, err) in
            
            if let json_b = wself?.json_handle_block
            {
                if JoTask.debugLog
                {
                    if wself?.if_log_response ?? false{
                        if let resp = response as? HTTPURLResponse
                        {
                            print("JoTask http response:\(resp.statusCode) \(String(describing: object))")
                        }
                        else{
                            print("JoTask response :\(String(describing: object))")
                        }
                    }
                }
//                let resp = DataResponse(request: nil,response:nil,data: nil,result: Result<Any>.success("没有上传文件".loc))
               
                
                let resp = DataResponse(request: nil, response: nil, data: nil, metrics: nil, serializationDuration: 1, result: Result<Any,JoError>.success("没有上传文件".loc))

                
                if let info = wself?.dataHandle(wself,object,wself?.url_value,wself?.apimode)
                {
//                    print("=====uuuuss|\(info.obj)")
                    json_b(info.status,info.message,info.obj,resp,wself)
                    wself?.__drop()
                    return
                }
                
                
                json_b(.error,"\("不包含解析数据".loc)\(#line)",nil,resp,wself)
                wself?.__drop()
                return
            }
            else{
                wself?.__drop()
                return

            }
        }
        return self
    }
    
    
    @discardableResult
    public func uploaRq() ->JoTask
    {
        
        _ = self.post
        
        if let r = self.request
        {
            r.cancel()
        }
        if JoTask.debugLog
        {
            if self.if_log_request
            {
                print("JoTask:\(method_value)|\(url_value)\nparameters:\(getParams())\nheaders:\(self.getHeaders())")
            }
        }
        

        weak var wself = self

        if let json_b = self.json_handle_block
        {
            
            
            if let f1 = self.files.first
            {
                self.request = AF.upload(f1.data, to: url_value, method: method_value, headers: HTTPHeaders(getHeaders()))
//                self.request = Alamofire.upload(f1.data, to: url_value, method: method_value, headers: self.getHeaders())
                
                //                self.request = Alamofire.upload(method_value, url_value, headers: self.getHeaders(), data: f1.data)
            }
            else
            {
                
//                let err = DataResponse(request: nil,response: nil,data: nil,result: Result<Any>.success("没有上传文件"))
                let err = DataResponse(request: nil, response: nil, data: nil, metrics: nil, serializationDuration: 1, result: Result<Any,JoError>.success("没有上传文件".loc))

                json_b(.error,"没有上传文件",nil,err,wself)
                return self
            }
            
       
            
            self.request?.responseJSON
                {
                    if JoTask.debugLog
                    {
                        if self.if_log_response
                        {
                            print("JoTask response:\($0)")
                        }
                    }
                    
                    if $0.value != nil
                    {
                        if let info = wself?.dataHandle(wself,$0.value ?? NSMutableDictionary(),wself?.url_value,wself?.apimode)
                        {
                            json_b(info.status,info.message,info.obj,$0,wself)
                            wself?.__drop()
                            return

                        }
                    }
                    

                    
                    json_b(.error,"获取数据失败(未知错误)",$0.value as AnyObject?,$0,wself)
                    wself?.__drop()
                    
                    return
                    
                    
            }
        }
        else if let text_b = self.text_handle_block
        {
            self.request?.responseString
                {
                    text_b(.success,"ok",$0.value as AnyObject?,$0,wself)
            }
            __drop()
            
        }
        
        return self
    }
    
    
    
}

